package com.stylefeng.guns.modular.wz.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.Consts;
import com.stylefeng.guns.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.common.persistence.dao.*;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.modular.wz.dao.WzQuestionDao;
import com.stylefeng.guns.modular.wz.dao.WzQuestionnaireDao;
import com.stylefeng.guns.modular.wz.service.IPfFileService;
import com.stylefeng.guns.modular.wz.service.impl.WzQuestionServiceImpl;
import com.stylefeng.guns.modular.wz.warpper.WzQuestionWarpper;
import com.stylefeng.guns.modular.wz.warpper.WzQuestionnaireWarpper;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import com.stylefeng.guns.modular.wz.service.IWzQuestionnaireService;

import java.util.*;

/**
 * 问卷控制器
 *
 * @author fengshuonan
 * @Date 2018-03-21 13:34:43
 */
@Controller
@RequestMapping("/wzQuestionnaire")
public class WzQuestionnaireController extends BaseController {

    private String PREFIX = "/wz/wzQuestionnaire/";

    @Autowired
    private IWzQuestionnaireService wzQuestionnaireService;
    @Autowired
    private WzQuestionDao wzQuestionDao;
    @Autowired
    private WzQuestionnaireDao wzQuestionnaireDao;
    @Autowired
    private WzQuestionServiceImpl wzQuestionService;
    @Autowired
    private IPfFileService pfFileService;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private PfOpenCityMapper openCityMapper;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzAdvUserMapper advUserMapper;
    @Autowired
    private WzQuestionMapper questionMapper;
    @Autowired
    private WzAnswerMapper answerMapper;

    /**
     * 跳转到问卷首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "wzQuestionnaire.html";
    }

    /**
     * 调查问卷首页
     */
    @RequestMapping("/index")
    public String list() {
        return PREFIX + "questionnaire.html";
    }

    /**
     * 跳转到添加问卷
     */
    @RequestMapping("/wzQuestionnaire_add")
    public String wzQuestionnaireAdd(Integer type, Model model) {
        model.addAttribute("type", type);
        return PREFIX + "wzQuestionnaire_add.html";
    }

    /**
     * 跳转到修改问卷
     */
    @RequestMapping("/wzQuestionnaire_update/{wzQuestionnaireId}")
    public String wzQuestionnaireUpdate(@PathVariable Long wzQuestionnaireId, Model model) {
        WzQuestionnaire wzQuestionnaire = wzQuestionnaireService.selectById(wzQuestionnaireId);
        model.addAttribute("item", wzQuestionnaire);
        model.addAttribute("status", wzQuestionnaire.getStatus());
        model.addAttribute("qType", wzQuestionnaire.getType());
        model.addAttribute("type", ConstantFactory.me().getDictsByName("问卷类型", wzQuestionnaire.getType()));
        model.addAttribute("coverUrl", Consts.DOMAIN + wzQuestionnaire.getCoverUrl());
//        model.addAttribute("delFlag",  ConstantFactory.me().getDictsByName("删除标记",wzQuestionnaire.getDelFlag()));
        LogObjectHolder.me().set(wzQuestionnaire);
        List<WzQuestion> questionsList = wzQuestionService.selectList(new EntityWrapper<WzQuestion>().eq("questionnaire_id", wzQuestionnaireId));
//        List<Long> list = new ArrayList<>();
//        for(int i = 0 ; i < questionIdList.size() ; i++) {
//            list.add(questionIdList.get(i).getQuestionId());
//        }
//        List<WzQuestion> questionsList=wzQuestionService.selectBatchIds(list);


        model.addAttribute("questionsList", questionsList);
        return PREFIX + "wzQuestionnaire_edit.html";
    }

    /**
     * 获取问卷列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition, Integer type, Integer questionnaireType, Integer status, String title) {
        Integer qtype = null;
        if (type == null & questionnaireType == 3) {
            type = 3;
        }
        if (type == null & questionnaireType == 4) {
            qtype = 3;
        }
        List<Map<String, Object>> wzQuestionnaireList = wzQuestionnaireDao.selectWzQuestionnaires(null, condition, type, qtype, status, title);
        return new WzQuestionnaireWarpper(wzQuestionnaireList).warp();
    }

    /**
     * 新增问卷
     */
    @Transactional
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(WzQuestionnaire wzQuestionnaire, String questionIds,String fileId) {
        wzQuestionnaire.setCreateTime(new Date());
        PfFile pfFile = pfFileService.selectOne(new EntityWrapper<PfFile>().eq("file_id",fileId));
        if (pfFile == null) {
            return SUCCESS_TIP.fail("找到不图片");
        }
        wzQuestionnaire.setCoverUrl(pfFile.getFileUrl());
        wzQuestionnaire.setPublishingType(1);
        wzQuestionnaire.setStatus(2);
        wzQuestionnaireService.insert(wzQuestionnaire);
        String[] ids = questionIds.split(";");
        for (int i = 0; i < ids.length; i++) {
            WzQuestion question = wzQuestionService.selectById(ids[i]);
            question.setQuestionnaireId(wzQuestionnaire.getQuestionnaireId());
            question.setStatus(2);
            boolean r = wzQuestionService.updateById(question);
        }
        return super.SUCCESS_TIP;
    }

    /**
     * 删除问卷
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Long wzQuestionnaireId) {
        WzQuestionnaire questionnaire = wzQuestionnaireService.selectById(wzQuestionnaireId);
        if (questionnaire.getStatus() == 1) {
            wzQuestionnaireService.deleteById(wzQuestionnaireId);
            List<WzQuestion> questions = questionMapper.selectList(new EntityWrapper<WzQuestion>().eq("questionnaire_id",wzQuestionnaireId));
            for(WzQuestion question:questions){
                question.setStatus(1);
                questionMapper.updateById(question);
            }
            return SUCCESS_TIP;
        } else {
            return SUCCESS_TIP.fail("只有待使用问卷才可删除!");
        }
    }

    /**
     * 删除问卷全部
     */
    @RequestMapping(value = "/deleteAll")
    @ResponseBody
    public Object deleteAll(@RequestParam Long wzQuestionnaireId) {
        WzQuestionnaire questionnaire = wzQuestionnaireService.selectById(wzQuestionnaireId);
        if (questionnaire.getStatus() == 1) {
            wzQuestionnaireService.deleteById(wzQuestionnaireId);
            List<WzQuestion> questions = questionMapper.selectList(new EntityWrapper<WzQuestion>().eq("questionnaire_id",wzQuestionnaireId));
            for(WzQuestion question:questions){
                List<WzAnswer> answers = answerMapper.selectList(new EntityWrapper<WzAnswer>().eq("question_id",question.getQuestionId()));
                for(WzAnswer answer:answers){
                    answerMapper.deleteById(answer);//删除答案
                }
                questionMapper.deleteById(question);//删除问题
            }
            return SUCCESS_TIP;
        } else {
            return SUCCESS_TIP.fail("只有待使用问卷才可删除!");
        }
    }

    /**
     * 问卷提交审核
     */
    @RequestMapping(value = "/checkQu")
    @ResponseBody
    public Object checkQu(@RequestParam Long wzQuestionnaireId) {
        WzQuestionnaire questionnaire = wzQuestionnaireService.selectById(wzQuestionnaireId);
        if (questionnaire.getStatus() == 2 || questionnaire.getStatus() == 4) {
            questionnaire.setStatus(3);
            wzQuestionnaireService.updateById(questionnaire);
            return SUCCESS_TIP;
        } else {
            return SUCCESS_TIP.fail("只有使用中和驳回问卷才可提交审核!");
        }
    }

    /**
     * 发布问卷
     */
    @Transactional
    @RequestMapping(value = "/release")
    @ResponseBody
    public Object release(@RequestParam Long wzQuestionnaireId) {
        WzQuestionnaire questionnaire = wzQuestionnaireService.selectById(wzQuestionnaireId);
        if (questionnaire.getStatus() == 5) {
            questionnaire.setStatus(6);
            wzQuestionnaireService.updateById(questionnaire);
            //保存为广告
            WzAdv adv = new WzAdv();
            adv.setStatus(5);
            adv.setPublishingType(1);
            adv.setCreateTime(questionnaire.getCreateTime());
            adv.setHasDetail(1);
            adv.setCoverUrl(questionnaire.getCoverUrl());
            adv.setScreenCity(questionnaire.getScreenCity());
            adv.setSubtype(questionnaire.getSubtype());
            adv.setQuestionnaireId(questionnaire.getQuestionnaireId().toString());
            adv.setTitle(questionnaire.getTitle());
            advMapper.insert(adv);
            //保存为广告用户
            List<WzUser> userList = new ArrayList<>();
            List<PfOpenCity> openCities = openCityMapper.selectList(new EntityWrapper<PfOpenCity>().eq("ad_code",questionnaire.getScreenCity()));
            if(openCities.get(0).getLevel() == 2){
                List<PfOpenCity> openCitieList = openCityMapper.selectList(new EntityWrapper<PfOpenCity>().eq("father_id",openCities.get(0).getId()));
                for(PfOpenCity openCity:openCitieList){
                    List<WzUser> users1 = userMapper.selectList(new EntityWrapper<WzUser>().eq("ad_code",openCity.getAdCode()));
                    userList.addAll(users1);
                }
            }else if(openCities.get(0).getLevel() == 3){
                    userList = userMapper.selectList(new EntityWrapper<WzUser>().eq("ad_code",questionnaire.getScreenCity()));
            }
            //保存广告用户
            for(WzUser user:userList){
                WzAdvUser advUser = new WzAdvUser();
                advUser.setAdvId(adv.getAdvId().toString());
                advUser.setCoverUrl(adv.getCoverUrl());
                advUser.setHasDetail(adv.getHasDetail());
                advUser.setSubtype(adv.getSubtype());
                advUser.setTitle(adv.getTitle());
                advUser.setUserCode(user.getUserCode());
                advUserMapper.insert(advUser);
            }
            return SUCCESS_TIP;
        } else {
            return SUCCESS_TIP.fail("只有审核通过问卷才可发布!");
        }
    }


    /**
     * 修改问卷
     */
    @Transactional
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(WzQuestionnaire wzQuestionnaire, String delQuestionIds, String questionIds) {
        //删除原答案
        if (StringUtils.isNotBlank(delQuestionIds)) {
            int c = wzQuestionService.selectCount(new EntityWrapper<WzQuestion>().eq("questionnaire_id", wzQuestionnaire.getQuestionnaireId()));
            String[] ids = delQuestionIds.split(";");
            if (ids.length >= c && questionIds == null) {
                return SUCCESS_TIP.fail("至少有一个问题!");
            }
            for (int i = 0; i < ids.length; i++) {
                WzQuestion question = wzQuestionService.selectById(ids[i]);
                question.setQuestionnaireId(0L);
                question.setStatus(1);
                boolean r = wzQuestionService.updateById(question);
            }
        }
        //增加新答案
        if (questionIds != null) {
            String[] ids = questionIds.split(";");
            for (int i = 0; i < ids.length; i++) {
                WzQuestion question = wzQuestionService.selectById(ids[i]);
                question.setQuestionnaireId(wzQuestionnaire.getQuestionnaireId());
                question.setStatus(2);
                boolean r = wzQuestionService.updateById(question);
            }
        }
        wzQuestionnaire.setUpdateTime(new Date());
        wzQuestionnaireService.updateById(wzQuestionnaire);
        return super.SUCCESS_TIP;
    }

    /**
     * 问卷详情
     */
    @RequestMapping(value = "/detail/{wzQuestionnaireId}")
    @ResponseBody
    public Object detail(@PathVariable("wzQuestionnaireId") Long wzQuestionnaireId) {
        return wzQuestionnaireService.selectById(wzQuestionnaireId);
    }

    /**
     * 添加问题
     */
    @RequestMapping(value = "/addQuestions")
    @ResponseBody
    public Object addQuestions(Integer type) {
        EntityWrapper<WzQuestion> ew = new EntityWrapper<>();
        ew.eq("type", type);
        ew.setSqlSelect("question_id as questionId,question,status");
        List<Map<String, Object>> list = wzQuestionService.selectMaps(ew.eq("status", 1));
        return new WzQuestionnaireWarpper(list).warp();
    }

    /**
     * 删除问题
     */
    @RequestMapping(value = "/deleteQuestion")
    @ResponseBody
    public Object deleteQuestions(Long questionId, WzQuestionnaire wzQuestionnaire) {
        Map<String, Object> map = new HashMap<>();
        map.put("question_id", questionId);
        map.put("questionnaire_id", wzQuestionnaire.getQuestionnaireId());
        return super.SUCCESS_TIP;
    }
}
